package com.rchat.pocmini.activity.recharge;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;

import com.airtalkee.sdk.AirtalkeeAccount;
import com.aso.common.http.bean.BaseBean;
import com.aso.common.http.delegate.HttpCallbackImpl;
import com.itsdf07.alog.ALog;
import com.rchat.pocmini.R;
import com.rchat.pocmini.activity.creategroup.CreateGroupPresenterImpl;
import com.rchat.pocmini.activity.fragment.groups.GroupsPresenterImpl;
import com.rchat.pocmini.bean.QueryPriceBean;
import com.rchat.pocmini.bean.RechargeResultBean;
import com.rchat.pocmini.bean.TradeNoBean;
import com.rchat.pocmini.bean2eventbus.EventBusAccountBean;
import com.rchat.pocmini.global.IntentKeyGlobal;
import com.rchat.pocmini.global.UrlsGlobal;
import com.rchat.pocmini.wxapi.Constants;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.regex.Pattern;

import static com.rchat.pocmini.global.HttpCodeGlobal.REQ_CODE_1051;
import static com.rchat.pocmini.global.HttpCodeGlobal.REQ_CODE_1052;
import static com.rchat.pocmini.global.HttpCodeGlobal.REQ_CODE_1053;

/**
 * @Description ：
 * @Author itsdf07
 * @Time 2017/9/27
 */

public class ReChargePresenterImpl extends RechargeContract.Presenter {
    /**
     * 页面来自哪里：
     *
     * @see com.rchat.pocmini.global.IntentKeyGlobal.IntentRecharge
     */
    private int mPageFrom = -1;

    private IWXAPI iwxapi;

    public static final int TRADE_TYPE_ID_MONTH = 1;
    public static final int TRADE_TYPE_ID_YEAR = 2;

    public static final int RECHARGE_MONTH = 3;
    public static final int RECHARGE_ONE_YEAR = 4;
    public static final int RECHARGE_TWO_YEAR = 5;
    public static final int RECHARGE_THREE_YEAR = 6;


    private String monthMoney = "";
    private String oneYearMoney = "";
    private String twoYearMoney = "";
    private String threeYearMoney = "";

    private String monthString = "";
    private String oneYearString = "";
    private String twoYearString = "";
    private String threeYearString = "";


    @Override
    public void onPStart() {
        super.onPStart();

        mPageFrom = mActivity.getIntent().getIntExtra(IntentKeyGlobal.IntentRecharge.INTENT_KEY_FROM, -1);
        ALog.d("mPageFrom = %s", mPageFrom);

        /** 测试微信支付 **/
        //将应用的appId注册到微信
        iwxapi = WXAPIFactory.createWXAPI(mActivity, Constants.APP_ID, true);
        iwxapi.registerApp(Constants.APP_ID);

        if (!isWeixinAvilible(mActivity)) {
            mView.showShortToast(R.string.wechat_no_install_error);
        }

    }

    @Override
    void queryPriceList() {
        mModel.queryPriceList(new HttpCallbackImpl<QueryPriceBean>() {

            @Override
            public void onStart() {
                mView.showLoading();
            }

            @Override
            public void onSuccess(QueryPriceBean queryPriceBean) {
                List<QueryPriceBean.DataBean.ProducePriceBean> data = queryPriceBean.getData().getProducePrice();


                for (QueryPriceBean.DataBean.ProducePriceBean b : data) {
                    if (b.getDateId().equals("1")) {//月
                        monthMoney = b.getPrice() + "";
                        monthString = b.getPrice() + "";
                    } else if (b.getDateId().equals("2")) {
                        oneYearMoney = b.getPrice() + "";
                        oneYearString = mActivity.getString(R.string.one_year) + b.getPrice() + mActivity.getString(R.string.yuan_charge);
                    } else if (b.getDateId().equals("3")) {
                        twoYearMoney = b.getPrice() + "";
                        twoYearString = mActivity.getString(R.string.two_year) + b.getPrice() + mActivity.getString(R.string.yuan_charge);
                    } else if (b.getDateId().equals("4")) {
                        threeYearMoney = b.getPrice() + "";
                        threeYearString = mActivity.getString(R.string.three_year) + b.getPrice() + mActivity.getString(R.string.yuan_charge);
                    }
                }

                if (!mModel.isNoShowRechargeInfoNextTime(mActivity)) {
                    mView.showRechargeInfoDialog(monthString, oneYearString, twoYearString, threeYearString);
                }

                mView.showPrice(monthString, oneYearString, twoYearString, threeYearString);

            }

            @Override
            public void onFailureResult(BaseBean bean) {

            }

            @Override
            public void onFinish() {
                mView.dismissLoading();
            }
        });
    }

    @Override
    void noShowRechargeInfoNextTime(boolean showNextTime) {
        mModel.noShowRechargeInfoNextTime(mActivity, showNextTime);
    }

    @Override
    void queryRechargeResult() {
        mModel.queryRechargeResult(AirtalkeeAccount.getInstance().getUserId(), new HttpCallbackImpl<RechargeResultBean>() {

            @Override
            public void onStart() {

            }

            @Override
            public void onSuccess(RechargeResultBean rechargeResultBean) {
                mView.showRechargeResult(rechargeResultBean.getData().getOrders());
            }

            @Override
            public void onFailureResult(BaseBean bean) {

            }

            @Override
            public void onFinish() {

            }
        });
    }

    @Override
    void updateAccountDate() {
        EventBusAccountBean bean = new EventBusAccountBean();
        switch (mPageFrom) {
            case IntentKeyGlobal.IntentRecharge.INTENT_VALUE_RECHARGE:
            case IntentKeyGlobal.IntentRecharge.INTENT_VALUE_VIPCHECK:
                bean.setTarget(this.getClass(), GroupsPresenterImpl.class, "onEventBusRequestAccount");
                break;
            case IntentKeyGlobal.IntentRecharge.INTENT_VALUE_CREATEGROUP:
                bean.setTarget(this.getClass(), CreateGroupPresenterImpl.class, "onEventBusRequestAccountStatus");
                break;
        }

        bean.setCurrentEvent(EventBusAccountBean.EVENT_ACCOUNT_DATE);
        EventBus.getDefault().post(bean);
    }

    @Override
    void recharge(int type, String month) {
        if (!isWeixinAvilible(mActivity)) {
            mView.showShortToast(R.string.wechat_no_install_error);
            return;
        }
        switch (type) {
            case RECHARGE_MONTH:
                if (null == month || "".equals(month)) {
                    mView.showShortToast(R.string.input_empty_error);
                    break;
                }
                if (!isInteger(month) || Integer.parseInt(month) >= 12 || Integer.parseInt(month) <= 0) {
                    mView.showShortToast(R.string.please_input_int);
                    break;
                }
                applyTradeNo(Integer.parseInt(month) * Float.parseFloat(monthMoney) + "", mActivity.getString(R.string.buy) + month + mActivity.getString(R.string.month), TRADE_TYPE_ID_MONTH);
                break;
            case RECHARGE_ONE_YEAR:
                applyTradeNo(Float.parseFloat(oneYearMoney) + "", mActivity.getString(R.string.buy_one_year), TRADE_TYPE_ID_YEAR);
                break;
            case RECHARGE_TWO_YEAR:
                applyTradeNo(Float.parseFloat(twoYearMoney) + "", mActivity.getString(R.string.buy_two_year), TRADE_TYPE_ID_YEAR);
                break;
            case RECHARGE_THREE_YEAR:
                applyTradeNo(Float.parseFloat(threeYearMoney) + "", mActivity.getString(R.string.buy_three_year), TRADE_TYPE_ID_YEAR);
                break;
        }

    }

    private void applyTradeNo(String money, String goodsName, int tradeTypeId) {
        mModel.applyTradeNo(goodsName, money, tradeTypeId, new HttpCallbackImpl<TradeNoBean>() {

            @Override
            public void onStart() {

            }

            @Override
            public void onSuccess(TradeNoBean tradeNoBean) {
                rechargeForWX(tradeNoBean.getData().getPrepayid(), tradeNoBean.getData().getNoncestr());
            }

            @Override
            public void onFailureResult(BaseBean bean) {
                mView.showShortToast(R.string.apply_trade_no_error);
            }

            @Override
            public void onFinish() {

            }
        });
    }

    private void rechargeForWX(String prepayid, String noncestr) {
        //开始支付
        PayReq req = new PayReq();
        req.appId = Constants.APP_ID;//appid
        req.partnerId = Constants.PARTNER_ID;//mch_ID
        req.prepayId = prepayid;//预支付订单号
        req.nonceStr = noncestr;//nonce_str
        req.timeStamp = Constants.genTimeStamp();//时间戳
        req.packageValue = Constants.PACKAGE;//常量，Sign=WXpay
        req.extData = "app data"; // optional
//            req.sign            = data.getString("sign");
        //生成签名
        SortedMap<Object, Object> params = new TreeMap<>();
        params.put("appid", req.appId);
        params.put("partnerid", req.partnerId);
        params.put("noncestr", req.nonceStr);
        params.put("package", req.packageValue);
        params.put("prepayid", req.prepayId);
        params.put("timestamp", req.timeStamp);
        req.sign = Constants.createSign(params);

//            Log.e(TAG,"req.prepayId:" + json.getString("prepayid"));
//            Log.e(TAG,"req.nonceStr:" + json.getString("noncestr"));
//            Log.e(TAG,"req.sign:" + json.getString("sign"));


        mView.showShortToast(R.string.prepare_recharge);
        // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
        iwxapi.sendReq(req);
    }


    //判断微信是否安装
    public static boolean isWeixinAvilible(Context context) {
        final PackageManager packageManager = context.getPackageManager();// 获取packagemanager
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equals("com.tencent.mm")) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     *     * 判断是否为整数  
     *     * @param str 传入的字符串  
     *     * @return 是整数返回true,否则返回false  
     */

    public static boolean isInteger(String str) {
        Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
        return pattern.matcher(str).matches();
    }

}
